package com.leyou.item.controller;

import com.leyou.item.pojo.Category;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    // @RequestParam("pid") 把请求中指定名称的参数给控制器中的形参赋值。
    @GetMapping("list")
    public ResponseEntity<List<Category>> queryCategoriesById(@RequestParam("pid") Long pid) {
        // 判断pid参数是否正常
        if (pid == null || pid < 0) {
            // return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
            // return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            // 下面的2个方式和下面一样，ResponseEntity的badRequest方法集成了HttpStatus.BAD_REQUEST  代表400
            return ResponseEntity.badRequest().build();
        }
        // 调用service的方法获取类目数据
        List<Category> categories = this.categoryService.queryCategoriesByPid(pid);
        // 判断数组是否为空或者null，返还的notFound对应HttpStatus.NOT_FOUND  代表404
        if (CollectionUtils.isEmpty(categories)) {
            return ResponseEntity.notFound().build();
        }
        // 数据没问题返还ok 200
        return ResponseEntity.ok(categories);
    }


    /**
     * 通过品牌id查询商品大类
     *
     * @return
     */
    @GetMapping("bid/{bid}")
    public ResponseEntity<List<Category>> queryByBrandId(@PathVariable("bid") Long bid) {
        List<Category> list = this.categoryService.queryByBrandId(bid);

        if (CollectionUtils.isEmpty(list)) {
            ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(list);
    }

    /**
     * 根据id查商品大类的名称
     */
    @GetMapping("names")
    public ResponseEntity<List<String>> queryNameByIds(@RequestParam("ids") List<Long> ids) {
        List<String> names = this.categoryService.queryNameByIds(ids);
        if (CollectionUtils.isEmpty(names)) {
            ResponseEntity.notFound().build();
        }

        return ResponseEntity.ok(names);
    }


    /**
     * 根据cid3来获取父类cid2和cid1的方法（用于前端面包屑展示）
     * @param id
     * @return
     */
    @GetMapping("all/level")
    public ResponseEntity<List<Category>> queryAllByCid3(@RequestParam("id") Long id) {
        List<Category> ids = this.categoryService.queryAllByCid3(id);
        if (CollectionUtils.isEmpty(ids)) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(ids);

    }
}

